package org.yh.moodpraise.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.yh.moodpraise.model.Message;
import org.yh.moodpraise.model.MoodVo;
import org.yh.moodpraise.model.User;
import org.yh.moodpraise.service.MoodService;
import org.yh.moodpraise.service.UserMoodPraiseRelService;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author: yh
 * @Date: 2020/6/21
 * @Description:
 */

@Controller
@RequestMapping("/praise")
public class PraiseController {
    @Autowired
    UserMoodPraiseRelService userMoodPraiseRelService;
    @Autowired
    MoodService moodService;

    /**
     * 常规利用数据库实现的逻辑
     */
    @GetMapping("/{userId}/db")
    public String praise(Model model, @PathVariable("userId") Integer userId, @RequestParam("moodId") Integer moodId) {
        //1. 更新userMoodPraiseRel表
        int res = userMoodPraiseRelService.addPraiseInfo(userId, moodId);
        if (res < 1) {
            Message msg = new Message(401, "更新userMoodPraiseRel表失败", null);
            model.addAttribute("message", msg);
            return "error";
        }
        //2. mood表点赞数增1
        res = moodService.updatePraiseNum(moodId);
        if (res < 1) {
            Message msg = new Message(401, "点赞数更新失败", null);
            model.addAttribute("message", msg);
            return "error";
        }
        Message msg = new Message(200, "点赞成功", null);
        model.addAttribute("message", msg);
        return "success";
    }

    /**
     * redis缓存，提供给用户的数据是缓存信息。利用定时任务周期性更新数据库。
     * 优点：避免频繁操作数据库
     */
    @GetMapping("/{userId}/redis")
    public String praiseForRedis(Model model, @PathVariable("userId") Integer userId, @RequestParam("moodId") Integer moodId, HttpSession session) {
        //点赞信息存入redis
        userMoodPraiseRelService.addPraiseInfoForRedis(userId, moodId);
        //用redis更新点赞信息，得到"最新"的视图对象
        List<MoodVo> moodVos = moodService.findMoodVosForRedis();
        //提供视图对象
        model.addAttribute("moodVos", moodVos);
        User user = (User) session.getAttribute("user");
        model.addAttribute("user", user);
        return "showMood";
    }

}
